using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.AttributeInfo;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Excel;
using Admin.NET.Application.Service.Manufacturer.Dto;
using Admin.NET.Core;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service.Manufacturer;

[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class DeviceManufacturerService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<DeviceManufacturer> _rep;

	public DeviceManufacturerService(SqlSugarRepository<DeviceManufacturer> rep)
	{
		_rep = rep;
	}

	/// <summary>
	/// 分页查询设备
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/deviceManufacturer/page")]
	public async Task<dynamic> Page([FromQuery] DeviceManufacturerInput input)
	{
		ISugarQueryable<DeviceManufacturer> query = _rep.Context.Queryable<DeviceManufacturer>().WhereIF(!string.IsNullOrWhiteSpace(input.Name), (DeviceManufacturer u) => u.Name.Contains(input.Name.Trim())).WhereIF(!string.IsNullOrWhiteSpace(input.Sn), (DeviceManufacturer u) => u.Sn.Contains(input.Sn.Trim()))
			.WhereIF(input.IsUse.HasValue, (DeviceManufacturer u) => (int?)u.IsUse == input.IsUse)
			.WhereIF(input.ProtocolType.HasValue, (DeviceManufacturer u) => (int?)u.ProtocolType == input.ProtocolType);
		ISugarQueryable<DeviceManufacturer> info = query.OrderByDescending((DeviceManufacturer u) => u.CreateTime).OrderBuilder(input);
		return await info.ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 设备导出
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/deviceManufacturer/pageexcel")]
	public async Task<IActionResult> ExportMeter([FromBody] DeviceManufacturerInput input)
	{
		string str = "设备库存-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> column = new List<string>();
		List<string> title = new List<string>();
		ISugarQueryable<DeviceManufacturer> query = _rep.Context.Queryable<DeviceManufacturer>().WhereIF(!string.IsNullOrWhiteSpace(input.Name), (DeviceManufacturer u) => u.Name.Contains(input.Name.Trim())).WhereIF(!string.IsNullOrWhiteSpace(input.Sn), (DeviceManufacturer u) => u.Sn.Contains(input.Sn.Trim()))
			.WhereIF(input.IsUse.HasValue, (DeviceManufacturer u) => (int?)u.IsUse == input.IsUse)
			.WhereIF(input.ProtocolType.HasValue, (DeviceManufacturer u) => (int?)u.ProtocolType == input.ProtocolType);
		List<DeviceManufacturerExcel> info = await (from u in query
			select new DeviceManufacturerExcel
			{
				Sn = u.Sn,
				CreateTime = u.CreateTime,
				IsUse = u.IsUse,
				Name = u.Name,
				ProtocolType = u.ProtocolType,
				UseName = u.UseName,
				UseTime = u.UseTime,
				Remark = u.Remark
			} into u
			orderby u.CreateTime descending
			select u).OrderBuilder(input).ToListAsync();
		info.ForEach(delegate(DeviceManufacturerExcel u)
		{
			if (u.IsUse == 0)
			{
				u.IsUseValue = "未使用";
			}
			else
			{
				u.IsUseValue = "已使用";
			}
			switch (u.ProtocolType)
			{
			case 0:
				u.ProtocolTypeValue = "DM780";
				break;
			case 1:
				u.ProtocolTypeValue = "DM780S";
				break;
			case 2:
				u.ProtocolTypeValue = "DM700";
				break;
			case 3:
				u.ProtocolTypeValue = "DM700S";
				break;
			}
		});
		column.AddRange(new string[7] { "Sn", "Name", "ProtocolTypeValue", "IsUseValue", "UseName", "UseTime", "CreateTime" });
		title.AddRange(new string[7] { "设备编号", "设备名称", "设备类型", "是否使用", "使用者", "使用日期", "创建日期" });
		MemoryStream memery = ExportToExcel.ExportToList(info.ToArray(), str, str, column.ToArray(), title.ToArray());
		App.HttpContext.Response.ContentType = "application/vnd.ms-excel";
		byte[] aa = memery.ToArray();
		return new FileStreamResult(new MemoryStream(aa), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}

	/// <summary>
	/// 增加设备
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/deviceManufacturer/add")]
	public async Task Add(DeviceManufacturerAdd input)
	{
		DeviceManufacturer entity = input.Adapt<DeviceManufacturer>();
		if (await _rep.IsAnyAsync((DeviceManufacturer u) => u.Sn == entity.Sn))
		{
			throw Oops.Oh(ErrorCodeEnum.R2002);
		}
		await _rep.InsertAsync(entity);
	}

	/// <summary>
	/// 删除设备
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/deviceManufacturer/delete")]
	public async Task Delete(BaseIdInput input)
	{
		DeviceManufacturer entity = await _rep.GetFirstAsync((DeviceManufacturer u) => u.Id == input.Id);
		if (entity.IsUse == 1)
		{
			throw Oops.Oh("当前设备已使用不允许删除");
		}
		await _rep.DeleteAsync(entity);
	}

	/// <summary>
	/// 更新设备
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/deviceManufacturer/edit")]
	[OperationLog("更新电表", "sn")]
	public async Task Update(DeviceManufacturerEdit input)
	{
		DeviceManufacturer entity = input.Adapt<DeviceManufacturer>();
		if (await _rep.IsAnyAsync((DeviceManufacturer u) => u.Sn == entity.Sn && u.Id != entity.Id))
		{
			throw Oops.Oh(ErrorCodeEnum.R2002);
		}
		await _rep.Context.Updateable(entity).UpdateColumns((DeviceManufacturer u) => new { u.Remark, u.Name, u.ProtocolType }).ExecuteCommandAsync();
	}

	/// <summary>
	/// 上传文件 导入设备
	/// </summary>
	/// <param name="file"></param>
	/// <param name="path"></param>
	/// <returns></returns>
	[HttpPost("/deviceManufacturer/uploadpdf")]
	public async Task UploadFile([Required] IFormFile file, string path = "")
	{
		ExcelUtil excelUtil = new ExcelUtil();
		List<DeviceManufacturerExcelAdd> list = excelUtil.ExcelToList<DeviceManufacturerExcelAdd>(file, new Dictionary<string, string>
		{
			{ "表序列号", "Sn" },
			{ "名称", "Name" },
			{ "协议类型", "ProtocolTypeValue" },
			{ "备注", "Remark" }
		});
		if (list.Where((DeviceManufacturerExcelAdd u) => string.IsNullOrWhiteSpace(u.ProtocolTypeValue)).Any())
		{
			throw Oops.Oh("当前协议类型存在空值");
		}
		List<string> imeilist = list.Select((DeviceManufacturerExcelAdd i) => i.Sn).ToList();
		DeviceManufacturer eleModel = await (from u in _rep.Context.Queryable<DeviceManufacturer>()
			where imeilist.Contains(u.Sn)
			select u).FirstAsync();
		if (eleModel != null)
		{
			throw Oops.Oh("当前表序列号已存在" + eleModel.Sn);
		}
		string disImei = (from u in imeilist
			group u by u into u
			select new
			{
				count = u.Count(),
				sn = u.Key
			} into u
			where u.count > 1
			select u).FirstOrDefault()?.sn;
		if (!string.IsNullOrEmpty(disImei))
		{
			throw Oops.Oh("当前表序列号存在重复" + disImei);
		}
		list.ForEach(delegate(DeviceManufacturerExcelAdd u)
		{
			u.ProtocolType = Convert.ToInt32(u.ProtocolTypeValue.Split('-')[1]);
		});
		List<DeviceManufacturer> addInfo = list.Adapt<List<DeviceManufacturer>>();
		_rep.InsertRange(addInfo.ToArray());
		await Task.Yield();
	}

	/// <summary>
	/// 导出列表excel
	/// </summary>
	/// <returns></returns>
	[HttpPost("/deviceManufacturer/templeteexcel")]
	public async Task<IActionResult> Templeteexcel()
	{
		string str = "设备入库模板-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> list = new List<string> { "表序列号", "名称", "协议类型", "备注" };
		Dictionary<string, List<string>> dic = new Dictionary<string, List<string>> { 
		{
			"协议类型",
			new List<string> { "DM780-0", "DM780S-1", "DM7O0-2", "DM700S-3" }
		} };
		ExcelUtil excelUtil = new ExcelUtil();
		MemoryStream stream = excelUtil.GetTemplate(list, dic, str);
		return new FileStreamResult(new MemoryStream(stream.ToArray()), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}
}
